import * as THREE from 'three';
import { CSS3DObject, CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

let scene, camera, renderer, css3DRenderer, controls;
let middle_shebei = {};

function init() {
    // 创建场景
    scene = new THREE.Scene();

    // 创建相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 10;

    // 创建WebGL渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // 创建CSS3D渲染器
    css3DRenderer = new CSS3DRenderer();
    css3DRenderer.setSize(window.innerWidth, window.innerHeight);
    css3DRenderer.domElement.style.position = 'absolute';
    css3DRenderer.domElement.style.top = '0';
    document.body.appendChild(css3DRenderer.domElement);

    // 创建控制器
    controls = new OrbitControls(camera, renderer.domElement);

    // 添加环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);

    // 添加平行光
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    directionalLight.position.set(1, 1, 1);
    scene.add(directionalLight);

    // 添加设备
    addTexturedPlane({
        imgURL: './images/souce_01.png',
        width: 107,
        height: 96,
        x: -10.7,
        y: -2.4,
        z: 0,
        renderOrder: 3,
        labelObj: {
            type: 'machine_1',
            name: '1号机台',
            position: [0.04999999999999999, 0.6934999823570249, 0],
        },
    });

    // 监听窗口大小变化
    window.addEventListener('resize', onWindowResize, false);

    // 开始动画循环
    animate();
}

function createLabel(object, data) {
    object.geometry.computeBoundingBox(); // 计算包围盒

    const labelDiv = document.createElement('div');
    labelDiv.className = 'label-wrapper';
    labelDiv.innerHTML = `
        <div class="label-bottom"></div>
        <div class="label-line-1"></div>
        <div class="label-line-2"></div>
        <div class="label-content">
            <h3 class="label-name">${data.name}</h3>
            <div class="label-item">进程:xxxx</div>
            <div class="label-item">进程:xxxx</div>
            <div class="label-item">进程:xxxx</div>
            <div class="label-item">进程:xxxx</div>
        </div>
    `;

    const label = new CSS3DObject(labelDiv);

    const p_x = (data.position || [])[0] || 0;
    const p_y = (data.position || [])[1] || object.geometry.boundingBox.max.y || 0;
    const p_z = (data.position || [])[2] || 0;

    if (data.position) {
        console.log(`bigScreen.html 201 [data.position]`, data.position);
    }

    label.position.set(p_x, p_y, p_z);

    // 调整CSS3D对象的缩放
    const scale = 0.01; // 根据需要调整这个值
    label.scale.set(scale, scale, scale);

    middle_shebei[data.name + '_xuanfu'] = label;
    console.log(`bigScreen.html 209 [middle_shebei['2号机台'].position]`, middle_shebei[data.name + '_xuanfu'].position);

    object.add(label);
}

function addTexturedPlane(obj) {
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load(obj.imgURL, function (texture) {
        texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
        texture.minFilter = THREE.LinearMipmapLinearFilter;
        texture.magFilter = THREE.LinearFilter;
        texture.generateMipmaps = true;
        texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;

        const cur_xishu = 0.02; // 缩小的系数
        const geometry = new THREE.PlaneGeometry(obj.width * cur_xishu, obj.height * cur_xishu);

        const material = new THREE.MeshBasicMaterial({
            map: texture,
            transparent: true,
            opacity: 1,
            side: THREE.DoubleSide,
            blending: THREE.NormalBlending,
        });
        material.map.colorSpace = THREE.SRGBColorSpace;

        const plane = new THREE.Mesh(geometry, material);
        plane.material.depthWrite = false;

        plane.position.set(obj.x, obj.y, obj.z);
        plane.renderOrder = obj.renderOrder || 0;

        scene.add(plane);

        if (obj.labelObj) {
            if (obj.labelObj.type === 'machine_1' || obj.labelObj.type === 'machine_2') {
                createLabel(plane, { ...obj.labelObj });
                middle_shebei[obj.labelObj.name] = plane;
            }
        }
    });
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    css3DRenderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
    css3DRenderer.render(scene, camera);
}

init();

